package api

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/cgs/notice/models"
	"cgs-server/server/cgs/notice/service"
	"cgs-server/server/model"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"net/http"
	"strconv"
)

func List(w http.ResponseWriter, r *http.Request) {

	noticeType, err := strconv.ParseInt(r.FormValue("NoticeType"), 10, 64)
	if err != nil {
		noticeType = -1
	}
	// 分页
	current, err := strconv.ParseInt(r.FormValue("Current"), 10, 64)
	if err != nil {
		current = 0
	}
	size, err := strconv.ParseInt(r.FormValue("Size"), 10, 64)
	if err != nil {
		size = 0
	}
	page := model.Page{
		Current: current,
		Size:    size,
	}
	//currentUser, err := server.GetCurrentUser(r)
	currentUser, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
	}
	pageResult := service.ListPage(page, noticeType, currentUser)
	_, _ = helper.WriteJSON(w, server.OK().WithData(pageResult))
}
func Count(w http.ResponseWriter, r *http.Request) {
	noticeType, err := strconv.ParseInt(r.FormValue("NoticeType"), 10, 64)
	if err != nil {
		noticeType = -1
	}
	currentUser, err := base.GetCurrentUser(r)
	countResult, err := service.Count(noticeType, currentUser)
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
	} else {
		var result []bson.M
		for _, v := range models.NoticeTypeArray {
			c := bson.M{
				"notice_type":  v,
				"notice_total": 0,
			}
			for _, v2 := range countResult {
				t1 := fmt.Sprintf("%.0f", v2["notice_type"])
				t2 := fmt.Sprintf("%d", v)

				if t1 == t2 {
					c["notice_total"] = v2["notice_total"]
				}
			}
			result = append(result, c)
		}
		helper.WriteJSON(w, server.OK().WithData(result))
	}

}

func Clear(w http.ResponseWriter, r *http.Request) {
	noticeType, err := strconv.ParseInt(r.FormValue("NoticeType"), 10, 64)
	if err != nil {
		noticeType = -1
	}
	currentUser, err := base.GetCurrentUser(r)
	_, err = service.Clear(noticeType, currentUser)
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
	} else {
		helper.WriteJSON(w, server.OK("clear ok"))
	}
}

func Send(w http.ResponseWriter, r *http.Request) {
	noticeType := r.FormValue("noticeType")
	if noticeType == "" {
		helper.WriteJSON(w, server.Fail("NoticeType is needed"))
	}
	userId := r.FormValue("userId")
	if userId == "" {
		helper.WriteJSON(w, server.Fail("UserId is needed"))
	}
	msg := r.FormValue("msg")
	if msg == "" {
		helper.WriteJSON(w, server.Fail("Msg is needed"))
	}
	//TODO check ntype
	ntype, _ := strconv.ParseInt(noticeType, 10, 64)
	service.SendNoticeApi(userId, msg, models.NoticeType(ntype))
}
